<!-- 首页，支持店铺装修 -->
<template>
  <view style="padding-bottom: env(safe-area-inset-bottom)">
    <s-layout title="" navbar="none">
      <view class="index-container">
        <view class="header">
          <view class="avatar">
            <s-block-item :type="blockType" />
          </view>
          <view class="entrance">
            <view class="drawn" @tap="handleDrawnOpen">
              <!-- <image src="../../static/01_09.gif" style="width: 100%; height: 100%"></image> -->
              <view class="common-style drawn-text">
                <view class="common-text-title">{{ $t('generate.handDrawn') }}</view>
                <view class="common-text-desc">{{ $t('index.personalDrawing') }}</view>
              </view>
            </view>
            <view class="generate">
<!--              <view class="common-style generate-text">-->
<!--                <view class="common-text-title">{{ $t('generate.aiModel') }}</view>-->
<!--                <view class="common-text-desc">{{ $t('generate.aiGenerateDesc') }}</view>-->
<!--              </view>-->
              <!-- <image src="../../static/01_06.gif" style="width: 100%; height: 100%"></image> -->
            </view>

          </view>
        </view>
        <view class="nav">
          <scroll-view class="scroll-view_H" :scroll-x="true" @scroll="scroll" scroll-left="120">
            <view class="nav_box">
              <view
                v-for="(item, index) in state.categoryList"
                :key="item.id"
                @tap="checkout(index)"
                :class="index === state.activeMenu ? 'nav_item1' : 'nav_item'"
              >
                {{ item.name }}
              </view>
            </view>
          </scroll-view>
          <!-- 	<view class="nav_box">
					<view v-for="(item, index) in categoryList" :key="item.id" @tap="checkout(item.id)">
						<text :class="item.id ==currentId ? 'nav_item1' : 'nav_item'">{{item.name}}</text>
					</view>
				</view> -->
        </view>
        <view class="scroll-box">
          <scroll-view class="scroll-view" :scroll-y="true" @scroll="scrollTop">
            <view class="content">
              <view class="content_box" v-for="item in imageData" :key="item.id">
                <view class="" @tap="startPrints(item.picUrl, item.name, item.id)">
                  <div class="protected-image" :style="{ backgroundImage: `url(${item.picUrl})` }">
                  </div>
                  <!--							<image :src="item.picUrl" mode=""  @contextmenu.prevent="blockRightClick"></image>-->
                  <view class="product">
                    <text style="color: #707070">{{ item.name }}</text>
                  </view>
                </view>
              </view>
            </view>
            <uni-load-more
              v-if="state.pagination.total > 0"
              :status="state.loadStatus"
              :content-text="{
                contentdown: $t('index.clickViewMore'),
              }"
              @tap="loadMore"
            />
          </scroll-view>
        </view>
        <!-- 	<s-block v-for="(item, index) in template.components" :key="index" :styles="item.property.style">
				<s-block-item :type="item.id" :data="item.property" :styles="item.property.style" />
			</s-block>
			<view class="nav_log">
				<uni-card spacing="0" padding="0" @tap="handleAiOpen">
					<image src="/static/print.png" mode="" style="width: 100%;height: 200rpx;"></image>
				</uni-card>
				<uni-card spacing="0" padding="0" @tap="handleDrawnOpen">
					<image src="/static/handdrawn.png" mode="" style="width: 100%;height: 200rpx;"></image>
				</uni-card>
			</view> -->
      </view>
    </s-layout>
  </view>
</template>

<script setup>
  import { onLoad, onPageScroll, onPullDownRefresh } from '@dcloudio/uni-app';

  import sheep from '@/sheep';
  import $share from '@/sheep/platform/share';
  import { showAuthModal, closeAuthModal } from '@/sheep/hooks/useModal';
  import { ref, reactive, computed } from 'vue';
  import { handleTree } from '@/sheep/util';
  import _ from 'lodash';
  import CategoryApi from '@/sheep/api/product/category';
  import SpuApi from '@/sheep/api/product/spu';
  import Device from '@/sheep/api/device/device';
  import DeviceApi from '@/sheep/api/device/device';
  import AuthApi from '@/sheep/api/member/auth';
  import { useI18n } from 'vue-i18n';
  // 隐藏原生tabBar
  uni.hideTabBar();
  const blockType = ref('UserCardNew');
  const { t } = useI18n();

  const imageData = ref([]);
  const state = reactive({
    categoryList: [],
    goodsList: [],
    pagination: {
      // 商品分页
      list: [], // 商品列表
      total: [], // 商品总数
      pageNo: 1,
      pageSize: 6,
    },
    activeMenu: 0,
    loadStatus: '',
  });

  const blockRightClick = (e) => {
    e.preventDefault(); /* 阻止右键菜单 */
    alert(t('index.imageSavingNotAllowed'));
  };

  const checkout = (idx) => {
    state.activeMenu = idx;
    imageData.value = state.categoryList[idx].children;
  };
  const scroll = (e) => {};
  const scrollTop = (e) => {};

  const handleAiOpen = () => {
    sheep.$router.go('/pages/generate/aiGenerate');
  };
  const handleDrawnOpen = () => {
    sheep.$router.go('/pages/generate/handDrawn');
  };
  async function getList() {
    const deviceId = DeviceApi.getDeviceSerial();
    const deviceInfo = await DeviceApi.getDeviceInfo(deviceId);

    if (deviceInfo.data.sceneId) {
      const { code, data } = await DeviceApi.getModelList(deviceId);
      if (code !== 0) {
        return;
      }
      state.categoryList = handleTree(data);
    } else {
      const { code, data } = await CategoryApi.getCategoryList();
      if (code !== 0) {
        return;
      }
      state.categoryList = handleTree(data);
    }

    //处理http图片转base64
    state.categoryList.forEach((item, index) => {
      state.categoryList[index].children.forEach((item, index) => {
        const { picUrl } = item;
        fetch(picUrl)
          .then((response) => response.blob())
          .then((blob) => {
            return new Promise((resolve, reject) => {
              const reader = new FileReader();
              reader.onloadend = () => {
                resolve(reader.result);
              };
              reader.onerror = reject;
              reader.readAsDataURL(blob);
            });
          })
          .then((base64Data) => {
            // 将原始数据信息和Base64编码后的URL合并
            const image = new Image();
            image.src = base64Data;
            image.onload = () => {
              const canvas = document.createElement('canvas');
              const ctx = canvas.getContext('2d');
              canvas.width = image.width;
              canvas.height = image.height;
              ctx.drawImage(image, 0, 0);

              // 获取图像数据
              const id = ctx.getImageData(0, 0, canvas.width, canvas.height);
              const data = id.data;

              // 定义要替换的颜色 (107, 48, 13)
              const targetColor = {
                r: 241,
                g: 186,
                b: 63,
              };

              // 遍历像素并修改颜色
              for (let i = 0; i < data.length; i += 4) {
                // 检查是否是黑色（RGB值接近0的像素）
                if (data[i] < 200 && data[i + 1] < 200 && data[i + 2] < 200) {
                  data[i] = targetColor.r; // 红色通道设置为 107
                  data[i + 1] = targetColor.g; // 绿色通道设置为 48
                  data[i + 2] = targetColor.b; // 蓝色通道设置为 13
                }
              }
              // 将处理后的数据重新绘制到画布上
              ctx.putImageData(id, 0, 0);
              item.picUrl = canvas.toDataURL('image/png');
            };
          })
          .catch((error) => {
            console.error('图片转换出错:', error);
          });
      });
    });
  }
  // 加载商品列表
  async function getGoodsList() {
    // 加载列表
    state.loadStatus = 'loading';
    const res = await SpuApi.getSpuPage({
      categoryId: state.categoryList[state.activeMenu].id,
      pageNo: state.pagination.pageNo,
      pageSize: state.pagination.pageSize,
    });
    if (res.code !== 0) {
      return;
    }
    // 合并列表
    state.pagination.list = _.concat(state.pagination.list, res.data.list);
    state.pagination.total = res.data.total;
    state.loadStatus = state.pagination.list.length < state.pagination.total ? 'more' : 'noMore';
  }
  // 加载更多商品
  function loadMore() {
    if (state.loadStatus === 'noMore') {
      return;
    }
    state.pagination.pageNo++;
    getGoodsList();
  }

  const srcImg = ref('');
  const printSrc = ref('');
  async function startPrints(val, name, categoryId) {
    srcImg.value = await base64(val);
    printSrc.value = srcImg.value.split('base64,')[1];
    uni.setStorageSync('printSrc', printSrc.value);
    uni.setStorageSync('printName', name);
    uni.setStorageSync('categoryId', categoryId);
    uni.setStorageSync('printType', 'category');
    sheep.$router.go('/pages/generate/print', { from: 'index' });
  }

  const base64 = (url) => {
    return new Promise((resolve) => {
      const image = new Image();
      // 先设置图片跨域属性
      image.crossOrigin = 'Anonymous';
      // 再给image赋值src属性，先后顺序不能颠倒
      image.src = url;
      image.onload = function () {
        const canvas = document.createElement('CANVAS');
        // 设置canvas宽高等于图片实际宽高
        canvas.width = image.width;
        canvas.height = image.height;
        canvas.getContext('2d').drawImage(image, 0, 0);
        // toDataUrl可以接收2个参数，参数一：图片类型，参数二： 图片质量0-1（不传默认为0.92）
        const dataURL = canvas.toDataURL('image/png');
        resolve(dataURL);
      };
      image.onerror = () => {
        resolve({
          message: '相片处理失败',
        });
      };
    });
  };

  onLoad(async (options) => {
    const params = new URLSearchParams(window.location.search);
    //获取设备码
    const deviceId = computed(() => sheep.$store('device').deviceId);
    await getList();
    checkout(0);

    const type = params.get('type');
    const uuid = params.get('uuid');
    if (type === 'bindUser' && deviceId && uuid) {
      // 是否登录
      const isLogin = computed(() => sheep.$store('user').isLogin);
      if (!isLogin.value) {
        sheep.$router.go('/pages/user/info');
      } else {
        const res = await DeviceApi.bindMember(uuid);
        if (res.code === 0) {
          uni.showToast({
            title: t('index.home.bindSuccess'),
            duration: 5000,
          });
        } else {
          uni.showToast({
            title: t('index.home.bindFailed'),
            duration: 2000,
          });
        }
      }
    }
    const mobile = params.get('mobile');
    const password = params.get('password');

    if (type === 'userLogin' && deviceId && mobile && password) {
      // 是否登录
      const isLogin = computed(() => sheep.$store('user').isLogin);
      if (!isLogin.value) {
        await AuthApi.login({
          mobile,
          password,
          socialCodeValid: true,
        });
      }
    }

    // #ifdef MP
    // 小程序识别二维码
    if (options.scene) {
      const sceneParams = decodeURIComponent(options.scene).split('=');
      options[sceneParams[0]] = sceneParams[1];
    }
    // #endif

    // 预览模板
    if (options.templateId) {
      sheep.$store('app').init(options.templateId);
    }

    // 解析分享信息
    if (options.spm) {
      $share.decryptSpm(options.spm);
    }

    // 进入指定页面(完整页面路径)
    if (options.page) {
      sheep.$router.go(decodeURIComponent(options.page));
    }
  });

  // 下拉刷新
  onPullDownRefresh(() => {
    sheep.$store('app').init();
    setTimeout(function () {
      uni.stopPullDownRefresh();
    }, 800);
  });

  onPageScroll(() => {});
</script>

<style lang="scss" scoped>
  .index-container {
    height: 100vh;
    display: flex;
    flex-direction: column;
  }
  .header {
    width: 100%;
    height: 210px;
    background-image: url('../../static/header.gif');
    background-repeat: no-repeat;
    background-size: cover;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx;
    box-sizing: border-box;

    .avatar {
      width: 48%;
      height: 190px;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 30rpx;
      background-color: #fff;
      margin-right: 30rpx;
    }

    .entrance {
      width: 48%;

      .common-style {
        width: 100%;
        height: 100%;
        border-radius: 15px;
        background-size: 100% 100%;
        background-repeat: no-repeat;
        background-position: center;
        padding: 20px;
        padding-top: 25px;
        box-sizing: border-box;
        .common-text-title {
          font-size: 20px;
          font-weight: bold;
        }
        .common-text-desc {
          font-size: 14px;
          margin-top: 4px;
        }
      }

      .generate {
        width: 100%;
        height: 90px;
        .generate-text {
          background-image: url('../../static/ai_draw_bg.png');
        }
      }

      .drawn {
        width: 100%;
        height: 90px;
        margin-top: 10px;
        .drawn-text {
          background-image: url('../../static/draw_bg.png');
          padding-top: 21px;
        }
      }
    }
  }

  .nav {
    width: 100%;
    margin-top: 10px;
    display: flex;
    justify-content: center;

    .nav_box {
      display: flex;
      align-items: center;
      box-sizing: border-box;
      width: 100%;
      height: 45px;
      padding: 0 20px;
      background-color: #f9e14f;
      border-radius: 30px;
      overflow-x: scroll;

      .nav_item {
        display: inline-block;
        color: #606060;
        // width: 100%;
        height: 20px;
        margin: 0 20px;
        white-space: nowrap;
        font-size: 16px;
      }

      .nav_item1 {
        font-size: 16px;
        display: inline-block;
        // width: 100%;
        height: 20px;
        margin: 0 20px;
        padding: 5px 0;
        color: #000000;
        font-weight: bold;
        white-space: nowrap;
        border-bottom: 2px solid #fff;
      }
    }
  }

  .scroll-view_H {
    width: 90%;
  }
  .scroll-box {
    flex: 1;
    overflow: hidden;
    margin-bottom: 10px;
    .scroll-view {
      width: 90%;
      height: 100%;
      background-color: #fff;
      border-radius: 10px;
      margin: -20px auto;
      // padding-top: 30px;
      padding: 30px 10px 20px 10px;

      .content {
        width: 100%;
        // height: 100%;
        display: flex;
        flex-wrap: wrap;
        gap: 46px;

        .content_box {
          width: 290rpx;
          height: 336rpx;
          background-color: #f3f3f3;
          border-radius: 20rpx;
          // padding: 0px 15px;
          box-sizing: border-box;
          margin-bottom: 20rpx;

          image {
            width: 100%;
            height: 280rpx;
            border-radius: 20rpx 20rpx 0 0;
          }

          .product {
            display: flex;
            justify-content: center;
            height: 40rpx;
            line-height: 40rpx;
            overflow: hidden;
          }
        }
      }
    }
  }

  .protected-image {
    width: 100%;
    height: 296rpx; /* 与原image元素保持一致 */
    background-size: 100% 100%;
    background-repeat: no-repeat;
    background-position: center;
  }

  /* 	.nav_log {
		width: 100%;
		height: 100%;
		display: flex;
	}

	.nav_log .uni-card {
		width: 50%;
		height: 200rpx;
	} */
</style>
